package com.oyjd.framework.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 简单javaBean与json相互转化工具类
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
public class JsonUtil {
	/**
	 * json转化到bean
	 * 
	 * @param jsonObj
	 * @param cls
	 * @param map
	 *            获得简单java bean的属性对应set方法的map
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private static Object jsonToBean(JSONObject jsonObj, Class<?> cls, Map<String, Method> map) {
		Object obj = null;
		try {
			obj = cls.newInstance();
			for (Iterator iterator = jsonObj.keys(); iterator.hasNext();) {
				String key = (String) iterator.next();
				Reflection.invoke(map.get(key), obj, jsonObj.get(key).toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

	/**
	 * json转化到bean
	 * 
	 * @param jsonObj
	 * @param cls
	 * @return
	 */
	public static Object jsonToBean(JSONObject jsonObj, Class<?> cls) {
		return jsonToBean(jsonObj, cls, Reflection.getSetMethods(cls));
	}

	/**
	 * jsons转化到beans
	 * 
	 * @param jsonArray
	 * @param cls
	 * @return
	 */
	public static List<Object> jsonArrayToBeans(JSONArray jsonArray, Class<?> cls) {
		List<Object> list = new ArrayList<Object>();
		Map<String, Method> map = Reflection.getSetMethods(cls);
		try {
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObj = jsonArray.getJSONObject(i);
				list.add(jsonToBean(jsonObj, cls, map));
			}
		} catch (Exception err) {
			err.printStackTrace();
		}
		return list;
	}

	/**
	 * bean 转化到 json对象
	 * 
	 * @param bean
	 * @return
	 */
	public static JSONObject beanToJson(Object bean) {
		JSONObject object = new JSONObject();
		if (null != bean) {
			try {
				Map<String, Method> map = Reflection.getSetMethods(bean.getClass());
				for (String key : map.keySet()) {
					object.put(key, Reflection.getPrivatePropertyValue(bean, key));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return object;
	}

	/**
	 * javabeans 转化到 jsonarray对象
	 * 
	 * @param bean
	 * @return
	 */
	public static JSONArray beansToJsonArray(List<?> list) {
		JSONArray array = new JSONArray();
		try {
			for (Object obj : list) {
				array.put(beanToJson(obj));
			}
		} catch (Exception err) {
			err.printStackTrace();
		}
		return array;
	}
}
